package com.cs.controller;

import com.cs.entity.Student;
import com.cs.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
@CrossOrigin
public class StudentController {
    @Autowired
    private StudentService service;
    private R success(Object data) {
        return new R(200, data);
    }

    private R failure(String msg) {
        return new R(500, msg);
    }
    @GetMapping()
    public R selectAll(){
        List<Student> students = service.selectAll();
        return students !=null && !students.isEmpty()?success(students):failure("暂无内容");
    }
    @GetMapping("/{id}")
    public R SelectById(@PathVariable String id){
        Student student = service.SelectById(Integer.parseInt(id));
        return student !=null?success(student):failure("暂无内容");
    }
    @GetMapping(params = {"studentName"})
    public R selectName(@RequestParam String studentName){
        List<Student> students = service.selectName(studentName);
        System.out.println(studentName);
        return success(students);
    }
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable String id){
        Boolean aBoolean = service.deleteById(Integer.parseInt(id));
        if (aBoolean){
            return success("成功");
        }else {
            return failure("失败");
        }
    }
    @PostMapping()
    public R insertStudent(@RequestBody Student student){
        Boolean aBoolean = service.insertStudent(student);
        if (aBoolean){
            System.out.println(student);
            return success("成功");

        }else {
            return failure("失败");
        }
    }
    @PutMapping()
    public R updateStudent(@RequestBody Student student){
        Boolean aBoolean = service.updateStudent(student);
        if (aBoolean){
            return success("成功");
        }else {
            return failure("失败");
        }
    }
}
